package org.webball.communication;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Sender extends Thread {

	private Socket socket;
	private ObjectOutputStream output;
	
	private Object toSend;
	
	public Sender(Socket s) throws IOException {
		socket = s;
		output = new ObjectOutputStream(socket.getOutputStream());
		output.flush();
		
		toSend = null;
	}
	
	public void run() {
		while(!interrupted()) {
			if(toSend != null) {
				try {
					output.writeObject(toSend);
					output.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
				finally {
					toSend = null;
				}
			}
			
			try {
				sleep(100);
			} catch (InterruptedException e) {
				this.interrupt();
				throw new RuntimeException(e);
			}
		}
		try {
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			output = null;
			socket = null;
		}
		
	}
	
	public void send(Object obj) {
		toSend = obj;
	}
}
